const {run} = require('runjs')
const path = require('path')
const fs = require('fs')
const chalk = require('chalk')
const ignorePath = "node_modules"
const os = require("os")

class Task {
	constructor(suffixName = ".css", map) {
		this.map = map;
		this.paths = this.getAllFilesSync(process.cwd(), suffixName);
		this.totalCount = this.paths.length;
		this.completedCount = 0;
		this.startFix();
	}

	startFix() {
		if (this.paths.length < 1) {
			console.log(chalk.red("======file not found======"))
		} else {
			const len = os.cpus().length;
			for (let i = 0; i < len; i++) {
				this.fixFile(this.paths.shift())
			}
		}
	}

	fixFile(filePath) {
		if (!filePath) {
			return
		}
		const commandStr = ` postcss -u autoprefixer -o ${filePath} ${filePath} ${this.map ? '' : '--no-map'}`
		run(commandStr, {async: true}).then(res => {
			this.completedCount = this.completedCount + 1;
			//console.log(chalk.green("======autoprefixer success======" + filePath))
			if (this.paths.length < 1) {
				if (this.completedCount === this.totalCount) {
					console.log(chalk.green("======success==files===="+this.totalCount))
				}
			} else {
				this.fixFile(this.paths.pop())
			}
		}).catch(reason => {
			console.log(chalk.red("======autoprefixer error======" + filePath))
		})
	}

	// getStyleFiles(filePath = "src", suffixName = '.css') {
	// 	const options = []
	// 	if (fs.statSync(filePath).isDirectory()) {
	// 		const files = fs.readdirSync(filePath);//扫描filePath文件夹下面的文件
	// 		if (files && files.length > 0) {
	// 			files.forEach(fileName => {
	// 				let realFilePath = path.resolve(filePath, fileName)
	// 				if (fileName.endsWith(suffixName)) {
	// 					options.push(realFilePath)
	// 				} else if (!filePath.startsWith(".") && !filePath.endsWith(ignorePath)) {
	// 					options.push(...this.getStyleFiles(realFilePath));
	// 				}
	// 			})
	// 		}
	// 	}
	// 	return options;
	// }
	getAllFilesSync(filePath = "src", suffixName = '.css') {
		const fileList = []
		let statSync = fs.statSync(filePath);
		if (statSync.isDirectory()) {
			const files = fs.readdirSync(filePath);//扫描filePath文件夹下面的文件
			if (files && files.length > 0) {
				files.forEach(fileName => {
					let realFilePath = path.resolve(filePath, fileName)
					fileList.push(...this.getAllFilesSync(realFilePath, suffixName))
				})
			}
		} else if (statSync.isFile()) {
			if (!suffixName || (suffixName && filePath.endsWith(suffixName))) {
				fileList.push(filePath)
			}
		}
		return fileList;
	}
}


module.exports = Task;
